<?php
# http://www.google.com/finance?q=USDJPY
date_default_timezone_set('Japan');

class Xurrency{
	
	public $from='USD';
	public $to='JPY';
	public $quantity=1;
	public $currency = 0;
	
	public function setFrom($val){
		$this->from = val;
	}
	public function setTo($val){
		$this->to = val;
	}
	
	public function setQuantity($val){
		$this->quantity = val;
	}
	
	function __construct($qf,$qt,$qq){
		$this->from = $qf;
		$this->to = $qt;
		$this->quantity = $qq;
		
		# 设置读取次数 如果现在时间和暂存时间的差大于10分钟则读完网络数据，反之则读取本地数据。
//		$file_handle = fopen(dirname(__FILE__)."../../temp/Xurrency", "r");
//		while (!feof($file_handle)) {
//		   $line = fgets($file_handle);
//		   echo $line;
//		}
//		fclose($file_handle);
		
		$this->getGoogleCurrency();
	}
	function getGoogleCurrency(){
		$source = file_get_contents('http://www.google.com/finance?q=' . $this->from . $this->to);
		$r_currency = '#<span class=bld>(.*)</span>#iUs';
		$result_currency;
		preg_match_all($r_currency,$source,$result_currency);
		$result_currency = $result_currency[1][0];
		$this->currency = substr($result_currency, 0, 6);
	}
	function getJson(){
		$json = array("ref"=>"error");
		if($this->currency != 0){
			$json = array(
				"ref"=>"OK",
				"from"=>$this->from,
				"to"=>$this->to,
				"currency"=>$this->currency,
				"quantity"=>$this->quantity,
				"exchange"=>$this->currency*$this->quantity,
				"date"=>date('Y/m/d H:i:s')
			);
		}
		return json_encode($json);
	}
}



$_xurrency = new Xurrency('USD','JPY',1);
if(isset($_GET['qf'])&&isset($_GET['qt'])&&isset($_GET['qq'])){
	$_xurrency->from = $_GET['qf'];
	$_xurrency->to = $_GET['qt'];
	$_xurrency->quantity = $_GET['qq'];
	$_xurrency->getGoogleCurrency();
}
print_r($_xurrency->getJson());





?>